package com.qwq.config;

import com.qwq.model.LcuApiInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Configuration
public class LcuApiConfiguration {
    private final static Logger _logger = LoggerFactory.getLogger(LcuApiConfiguration.class);

    @Bean
    public LcuApiInfo getLcuApiInfo() throws IOException {
        String os = System.getProperty("os.name");
        _logger.info("当前系统:{}", os);
        // windows下才执行代码
        if (os.startsWith("Windows")) {
            _logger.info("正在获取基础信息......");
            Process process = Runtime.getRuntime().exec("WMIC PROCESS WHERE name=\"LeagueClientUx.exe\" GET commandline");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String lineText;
            StringBuilder stringBuilder = new StringBuilder();
            while ((lineText = bufferedReader.readLine()) != null) {
                stringBuilder.append(lineText);
            }
            String allCmdExecResult = stringBuilder.toString();
            Pattern pattern1 = Pattern.compile("\"--remoting-auth-token=.+?\"");
            Matcher matcher1 = pattern1.matcher(allCmdExecResult);
            String temp;
            String token = null;
            if (matcher1.find()) {
                temp = matcher1.group(0);
                token = temp.split("=")[1].replace("\"", "");
            }
            String port = null;
            Pattern pattern2 = Pattern.compile("\"--app-port=.+?\"");
            Matcher matcher2 = pattern2.matcher(allCmdExecResult);
            if (matcher2.find()) {
                temp = matcher2.group(0);
                port = temp.split("=")[1].replace("\"", "");
            }
            LcuApiInfo lcuApiInfo = new LcuApiInfo();
            lcuApiInfo.setToken(token);
            lcuApiInfo.setPort(port);
            if (StringUtils.hasText(lcuApiInfo.getPort()) && StringUtils.hasText(lcuApiInfo.getToken())) {
                _logger.info("获取基础信息完成");
                _logger.info(lcuApiInfo.toString());
            } else {
                _logger.error("获取基础信息失败！！！");
                _logger.error(allCmdExecResult);
            }
            return lcuApiInfo;
        } else {
            _logger.error("国服英雄联盟不支持当前系统，无法使用本软件");
            return new LcuApiInfo();
        }
    }
}
